import { useRequest } from 'ahooks';
import {
  Button,
  Space,
  Table,
  Badge,
  Popconfirm,
  Skeleton
} from 'antd';
import { useState, useCallback, useEffect } from 'react';
import { useHistory } from 'react-router-dom';

import * as APIS from '../../../../constants/api-constants';
import QuestionniareIncrease from '../../questionnaire-increase';

interface DetailProps {
  currentTemplateUuid: string | undefined;
}

export default ({
  currentTemplateUuid
}: DetailProps) => {
  if (!currentTemplateUuid) {
    return <Skeleton active />;
  }

  const history = useHistory();
  const [createVisable, setCreateVisable] = useState<boolean>(false);
  const [questionnaires, setQuestionnaires] = useState<
    Questionnaire.QuestionnaireItem[]
  >([]);

  /**
   * 获取当前模板对应的问卷列表
   */
  const { run: requestQuestionnaire, loading } = useRequest((templateUuid) => ({
    url: APIS.QUESTIONNAIRE_LIST,
    method: 'GET',
    params: {
      uuid: templateUuid
    }
  }), {
    manual: true,
    onSuccess: (result) => {
      const { questionnaires: currentQuestionnaires } = result.data;
      setQuestionnaires(currentQuestionnaires);
    },
  });

  /**
   * 删除问卷
   */
  const {
    run: requestDeleteQuestionnaire,
    loading: deleteQuestoinnaireLoading
  } = useRequest((questionnaireUuid) => ({
    url: APIS.QUESTIONNAIRE,
    method: 'DELETE',
    data: { uuid: questionnaireUuid }
  }), {
    manual: true,
    onSuccess: () => {
      console.log('success');
    },
    onError: () => {
    }
  });

  const handleDeleteQuestionnaire = useCallback(
    async (questionnaireUuid: string, templateUuid: string) => {
      await requestDeleteQuestionnaire(questionnaireUuid);
      await requestQuestionnaire(templateUuid);
    }, []
  );

  useEffect(() => {
    requestQuestionnaire(currentTemplateUuid);
  }, [currentTemplateUuid]);

  const columns = [
    {
      title: '二级问卷名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '问卷开启状态',
      key: 'open',
      dataIndex: 'open',
      width: 150,
      render: (record: number) => (
        record ? (
          <span>
            <Badge status="success" />
            开启
          </span>
        ) : (
          <span>
            <Badge status="error" />
            关闭
          </span>
        )
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (record: Questionnaire.QuestionnaireItem) => (
        <Space size="middle">
          <Popconfirm
            title="删除后该二级问卷后无法找回！是否删除?"
            onConfirm={() => {
              handleDeleteQuestionnaire(
                record.uuid, currentTemplateUuid
              );
            }}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
          <Button
            type="link"
            size="small"
            onClick={() => {
              history.push(`/home/questionnaireDetail/${currentTemplateUuid}/${record.uuid}`);
            }}
          >
            配置与详情
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <>
      <Space direction="vertical" style={{ width: '100%' }}>
        <Button
          type="primary"
          onClick={() => {
            setCreateVisable(true);
          }}
        >
          增加二级问卷
        </Button>
        <Table
          loading={loading || deleteQuestoinnaireLoading}
          style={{ width: '100%' }}
          columns={columns}
          dataSource={questionnaires}
          pagination={{ pageSize: 5 }}
          rowKey={(questionnaire) => questionnaire.uuid}
        />
      </Space>

      <QuestionniareIncrease
        visable={createVisable}
        setVisable={setCreateVisable}
        templateUuid={currentTemplateUuid}
        requestQuestionnaire={requestQuestionnaire}
      />
    </>
  );
};
